﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using PortalCurriculo.Util.CustomControls.ListViewObjects;

namespace PortalCurriculo.Util.CustomControls
{
    public class ListView : System.Web.UI.WebControls.ListView
    {
        #region Order

        #region Order enum

        public enum Order
        {
            Ascending,
            Descending
        }

        #endregion

        private const string OrderAttribute = "order";
        private const string AscendentOrder = "asc";
        private const string DescendentOrder = "desc";

        public void OrderBy<T>(List<T> items, string linkButtonName, string columnToOrder)
        {
            var linkButton = (LinkButton)FindControl(linkButtonName);

            if (linkButton.Attributes[OrderAttribute] == null)
                linkButton.Attributes.Add(OrderAttribute, AscendentOrder);

            if (linkButton.Attributes[OrderAttribute] == DescendentOrder)
            {
                linkButton.Attributes[OrderAttribute] = AscendentOrder;

                items = ApplyOrder(items.AsQueryable(), columnToOrder, "OrderBy").ToList();
            }
            else
            {
                linkButton.Attributes[OrderAttribute] = DescendentOrder;
                items = ApplyOrder(items.AsQueryable(), columnToOrder, "OrderByDescending").ToList();
            }

            DataSource = items;
            DataBind();
        }

        public void OrderBy<T>(List<T> items, Order order, string columnToOrder)
        {
            items =
                ApplyOrder(items.AsQueryable(), columnToOrder,
                           order == Order.Descending ? "OrderByDescending" : "OrderBy").ToList();

            DataSource = items;
            DataBind();
        }

        private static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName)
        {
            string[] props = property.Split('.');
            Type type = typeof(T);
            ParameterExpression arg = Expression.Parameter(type, "x");
            Expression expr = arg;
            foreach (string prop in props)
            {
                // use reflection (not ComponentModel) to mirror LINQ 
                PropertyInfo pi = type.GetProperty(prop);
                expr = Expression.Property(expr, pi);
                type = pi.PropertyType;
            }
            Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
            LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
            object result = typeof(Queryable).GetMethods().Single(
                method => method.Name == methodName
                          && method.IsGenericMethodDefinition
                          && method.GetGenericArguments().Length == 2
                          && method.GetParameters().Length == 2)
                .MakeGenericMethod(typeof(T), type)
                .Invoke(null, new object[] { source, lambda });
            return (IOrderedQueryable<T>)result;
        }

        #endregion

        //#region Automatic ListView

        //public TableStructure TableStructure { get; set; }

        //public void DataBind<T>(List<Field> fields)
        //{
        //    DataBind<T>(fields, null);
        //}

        //public void DataBind<T>(List<Field> fields, List<Control> actionControls)
        //{
        //    if (fields != null)
        //    {
        //        ItemPlaceholderID = "phItem";

        //        LayoutTemplate = new LayoutTemplate(fields, TableStructure);
        //        ItemTemplate = new ItemTemplate<T>(fields, DataSource, actionControls);
        //    }

        //    base.DataBind();
        //}

        //#endregion
    }
}